package 剑指offer.demo_41_滑动窗口的平均值;

import java.util.ArrayList;

/**
 * 自己实现一个类, 实现里面的2种方法
 *
 * 初始化, MovingAverage(int size) , 用来初始化窗口的大小, 也就是一个构造方法
 *
 * double next (int val) , 每次调用这个方法, 都会往滑动窗口中添加一个数据, 并且返回这个窗口中的平均值
 *
 *
 */
public class MovingAverage {

    public ArrayList<Double> arrayList; // 用来放这个成员的值
    public int size;// 用来指定窗口的大小
    public int count; // 用来计算这个已经放进这个集合中的元素的个数
    public double sum;// 用来计算窗口内的总和

    public MovingAverage(int size){
        this.size=size;
        arrayList=new ArrayList<Double>();

    }

    public double next(double val){
        count++;// 计数器++
        sum+=val;
        double avg;
        arrayList.add(val);
        if (count<=size){
             avg=  sum/count;
        }else {
            double v = sum - arrayList.get(0);
            arrayList.remove(0);
             avg =  v/size;

        }

        return avg;
    }

    public static void main(String[] args) {
        MovingAverage movingAverage = new MovingAverage(5);

        double v2 = movingAverage.next(12009);
        double v3 = movingAverage.next(1965);
        double v4 = movingAverage.next(-8516);
        double v5 = movingAverage.next(-16446);
        double v6 = movingAverage.next(7870);
        double v7 = movingAverage.next(25545);
        double v8 = movingAverage.next(-21028);
        double v9 = movingAverage.next(18430);
        double v10 = movingAverage.next(-23464);

        //System.out.println(v1);
        System.out.println(v2);
        System.out.println(v3);
        System.out.println(v4);
        System.out.println(v5);
        System.out.println(v6);
        System.out.println(v7);
        System.out.println(v8);
        System.out.println(v4);
        System.out.println(v10);
    }
}
